import { useState, useEffect } from 'react'
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import './index.scss'


export default function NewsEditor(props) {
  const [editorState, setEditorState] = useState(EditorState.createEmpty())

  const onEditorStateChange = editorState => {
    setEditorState(editorState)
  }

  useEffect(() => {
    // props.content为undefined 说明此时NewsAdd为父组件，没给本组件传content
    if (props.content === undefined) return
    const contentBlock = htmlToDraft(props.content);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorFatherState = EditorState.createWithContent(contentState);
      setEditorState(editorFatherState)
    }
  }, [props.content])

  return (
    <div style={{ height: "340px", overflow: 'auto', border: '1px solid #EFF2F5' }}>
      <Editor
        editorState={editorState}
        onEditorStateChange={onEditorStateChange}
        toolbarClassName="toolBar"
        placeholder='请输入新闻内容...'
        onBlur={() => {
          props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
        }}
      />
    </div>
  )
}